<template>
<div class="box">
    <div class="register">
        <h1>登录</h1>
        <div class="register-form">
            <el-form class="register-form-box"
            ref="formRef"
            :model="formData"
            :rules="formRules"
            >
                <el-form-item 
                label="用户名:"
                :prop="'username'"
                >
                    <el-input
                    v-model="formData.username"
                    :prefix-icon="User"
                    placeholder="请输入用户名"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item 
                label=" 密码:"
                :prop="'password'"
                >
                    <el-input
                    v-model="formData.password"
                    :prefix-icon="Lock"
                    placeholder="请输入密码"
                    show-password
                    >
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <!-- 添加 loading 状态 -->
                    <el-button type="primary" @click="submitLogin" :loading="loading">登录</el-button>
                    <el-button type="info" @click="toRegister">注册</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</div>
</template>

<script setup lang="ts"> 
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// 导入登录 API
import type { LoginDTO } from '@/api/auth'
import { AuthApi } from '@/api/auth'


const router = useRouter()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 表单数据
const formData = ref<LoginDTO>({
    username: '',
    password: '',
})

// 表单验证规则
const formRules = reactive({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

/**
 * 跳转到注册页
 */
const toRegister = () => {
    router.push('/')
}

/**
 * 登录提交处理
 * 使用 auth.ts 中的 login API 进行登录
 */
const submitLogin = async () => {
    // 表单验证
    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) {
        ElMessage({
            message: '请检查输入的信息',
            type: 'error'
        })
        return
    }
    // 设置加载状态
    loading.value = true
    try {
        // 调用登录 API
        const response = await AuthApi.login(formData.value)
        console.log(response)
        // 检查响应状态
        if (response.code === 1) {
            // 登录成功处理
            const { accessToken, userInfo } = response.data     
            // 存储 token 到本地存储
            localStorage.setItem('token', accessToken)
            // 存储用户信息到本地存储
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
            // 显示成功消息
            ElMessage({
                message: '登录成功',
                type: 'success'
            })
            
            // 延迟跳转到首页
            setTimeout(() => {
                router.push('/index')
            }, 1000)
        } else {
            // 业务错误处理（通常不会到这里，因为 request 拦截器已处理）
            ElMessage({
                message: response.msg || '登录失败',
                type: 'error'
            })
        }
    } catch (error) {
        // 网络错误或其他异常（request 拦截器已显示错误消息）
        console.error('登录失败:', error)
        // 这里可以添加额外的错误处理逻辑
    } finally {
        // 无论成功失败都要关闭加载状态
        loading.value = false
    }
}
</script>

<style scoped>
.box {
    width: 100%;
    height: 100vh;
    background-image: url('../../assets/auth/authbg.jpg');
    background-size: cover;
    background-repeat: no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
}

.register {
    width: 500px;
    height: 400px;
    background-color: rgba(255, 255, 255, 0.7);
    text-align: center;
    border-radius: 30px;
}

.register-form {
    margin: 0 auto;
    width: 60%;
    height: 70%;
    display: flex;
    text-align: right;
}

.register-form-box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}
</style>